package com.xh.jf_blog.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.xh.jf_blog.bean.Token;
import com.xh.jf_blog.common.util.R;
import com.xh.jf_blog.mapper.TokenMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author PangJunjie
 * @Date 2024/2/19/019
 */
public class VipLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenMapper tokenMapper;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        /*统一处理中文乱码*/
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        if (StringUtils.isEmpty(token)) {
            response.getWriter().println(JSON.toJSON(R.error(401, "未携带token！")));
        } else {
            Token tokenBean = tokenMapper.getByToken(token);
            if (tokenBean == null || tokenBean.getExpires().getTime() < System.currentTimeMillis()) {
                response.getWriter().println(JSON.toJSON(R.error(401, "token失效！")));
            } else {
                request.getSession().setAttribute("vipInfo", tokenBean.getUserinfo());
                return true;

            }
        }
        return false;
    }
}
